import axios from 'axios';
import router from '@/router';
import {ElMessage} from "element-plus"; // 引入 Vue Router

const service = axios.create({

    baseURL: '/api', // 与代理配置匹配
    timeout: 20000
});

service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');

        console.log(localStorage);
        console.log(token);
        if (token) {
            // config.headers['token'] = `Bearer ${token}`;
            config.headers['Authorization'] = token;
        }

        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    response => {
        const res = response.data
        if(res.code === 403){
            ElMessage.error('权限不足，请联系管理员')
        }
        return response;
    },
    error => {
        if (error.response.status === 401) {
            localStorage.removeItem('token');
            router.push('/login');
        }
        return Promise.reject(error);
    }
);

export default service;